package com.bayair.doctor.ui.login;


import android.text.TextUtils;

import com.bayair.doctor.biz.helper.SpSetting;
import com.bayair.doctor.biz.im_helper.IMHelper;
import com.bayair.doctor.data.bean.IMSignKey;
import com.bayair.doctor.data.bean.LoginResp;
import com.bayair.doctor.mvp.BasePresenter;
import com.bayair.doctor.mvp.annotation.InjectModel;
import com.bayair.doctor.data.bean.VerityResp;
import com.bayair.doctor.net.RxFunction;
import com.bayair.doctor.net.RxSchedulers;
import com.bayair.doctor.biz.helper.SpDoctor;
import com.bayair.doctor.utils.RegexUtils;
import com.bayair.doctor.utils.log.KLog;

/**
 * Author: tuyrt7
 * Date: 2019/9/29 9:54
 * Description:
 */
public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {

    @InjectModel
    LoginModel mLoginModel;

    private String phoneNum;
    private LoginResp loginResp;
    private IMSignKey key;

    @Override
    public void verity() {
        String phoneNum = getView().getPhoneNum();
        if (!checkPhoneNum(phoneNum)) {
            getView().resetVerity();
            return;
        }

        //发送获取验证码的请求
        mLoginModel.verity(phoneNum)
                .map(new RxFunction<>())
                .compose(RxSchedulers.io_main())
                .subscribe(new ObserverOnRecycler<VerityResp>() {
                    @Override
                    public void onNext(VerityResp verityResp) {
                        log("结果：" + verityResp);
                    }
                });

    }

    @Override
    public void login() {
        phoneNum = getView().getPhoneNum();
        String authCode = getView().getAuthCode().trim();


        if (!checkPhoneNum(phoneNum) || !checkAuthCode(authCode)) {
            return;
        }
        //检查checkbox
        if (!getView().isCheckAgree()) {
            getView().notifyNoCheck();
            return;
        }

        SpSetting.setPhone(phoneNum);

        getView().onLoading();
        mLoginModel.login(phoneNum, authCode)
                .map(new RxFunction<>())
                .flatMap(loginResp -> {
                    //保存登录响应
                    this.loginResp = loginResp;
                    //转换获取IM登录需要的ImSighKey
                    return mLoginModel.getSignKey(loginResp.getNewtoken());
                })
                .map(new RxFunction<>())
                .compose(RxSchedulers.io_main())
                .subscribe(new ObserverOnRecycler<IMSignKey>() {
                    @Override
                    public void onNext(IMSignKey imSignKey) {
                        key = imSignKey;

                        spCache();
                        loginIM();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getView().loginFail("");
                    }
                });
    }

    /**
     sp 缓存登录服务获得响应的属性
     */
    private void spCache() {
        SpDoctor.setImName(loginResp.getImname());
        SpDoctor.setToken(loginResp.getNewtoken());
        SpDoctor.setInquiry(loginResp.isInquiryswitch());
        SpDoctor.setReceive(loginResp.isReceiveoffmsg());
        SpDoctor.setIMSignKey(key.getSignkey());
    }

    /**
     IM登录（直到im登录完成整个登录流程才算成功）
     */
    private void loginIM() {
        IMHelper.loginIM(new IMHelper.LoginListener() {
            @Override
            public void onError() {
                getView().loginFail("");
            }

            @Override
            public void onSuccess() {
                SpSetting.setLogin(true);

                getView().loginSuccess();
            }
        });
    }


    private boolean checkAuthCode(String authCode) {
        if (TextUtils.isEmpty(authCode) ) {
            toast("请输入验证码");
            return false;
        }
        if (authCode.length() < 4) {
            toast("验证码输入错误");
            return false;
        }
        return true;
    }

    private boolean checkPhoneNum(String phoneNum) {
        if (TextUtils.isEmpty(phoneNum)) {
            toast("请输入您的手机号码");
            return false;
        }

        if (!RegexUtils.validateMobilePhone(phoneNum)) {
            toast("手机号码输入错误");
            return false;
        }
        return true;
    }
}
